package com.example.roam.ui.activity;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.roam.R;
import com.example.roam.api.HttpUpload;
import com.example.roam.model.gson.InformationHead;
import com.example.roam.ui.adpter.InformationHeadAdapter;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.StatusBarUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Illustration
 *
 * @author dengqing
 * @time 2021/10/17
 * @function InformationActivity的用户头像选择界面
 */

public class InformationHeadActivity extends AppCompatActivity implements View.OnClickListener {
    private String head = "";//头像图片id
    private String headPath = "";
    private Button btn_cancel, btn_confirm;
    private ImageView img_back, img_album, img_photo;
    private GridView gridView_head;
    private List<String> list_haed;
    private InformationHeadAdapter adapter_head;
    int headPosition = 0;
    private static final int REQUEST_CODE_CHOOSE = 20;
    private ArrayList<Uri> mSelected;
    private ArrayList<String> filePathArray = new ArrayList<>();
    private int head_select = 0;  // 1 系统， 2 上传
    private boolean isUpdate;

    //软件提供的头像
    private void initHead() {
        gridView_head = (GridView) findViewById(R.id.gridView_head);
        //添加数据
        list_haed = new ArrayList<>();
        list_haed.add(R.drawable.head_man1 + "");
        list_haed.add(R.drawable.head_woman1 + "");
        list_haed.add(R.drawable.head_man2 + "");
        list_haed.add(R.drawable.head_woman2 + "");
        list_haed.add(R.drawable.head_man3 + "");
        list_haed.add(R.drawable.head_woman3 + "");
        adapter_head = new InformationHeadAdapter(InformationHeadActivity.this, list_haed, false);
        gridView_head.setAdapter(adapter_head);
        gridView_head.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                head_select=1;
                adapter_head.setHead_select(1);
                adapter_head.chiceState(position);
                head = list_haed.get(position);
                img_album.setImageResource(R.drawable.img);
                headPosition = position;
                Toast.makeText(InformationHeadActivity.this, "您选择了头像" + (position + 1), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information_head);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        Intent intent = getIntent();
        isUpdate = intent.getBooleanExtra("isUpdate", false);
        initView();
        initHead();
    }

    //初始化组件
    private void initView() {
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_confirm = findViewById(R.id.btn_confirm);
        img_back = findViewById(R.id.img_back);
        img_album = findViewById(R.id.img_album);
        img_photo = findViewById(R.id.img_photo);
        img_photo.setOnClickListener(this);
        img_back.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        img_album.setOnClickListener(this);
    }

    private static final String TAG = "InformationHeadActivity";
    @Override
    public void onClick(View view) {
        Intent intent = getIntent();
        switch (view.getId()) {
            case R.id.btn_cancel:
                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.btn_confirm:
                if ((head_select != 0) && (!head.isEmpty())) {
                    if(!isUpdate) {
                        intent.putExtra("headPath", headPath);
                        intent.putExtra("head_select", head_select);
                        if (head_select == 1) {
                            systemHeadImg(headPosition); // 设置系统头像
                        }
                        setResult(RESULT_OK, intent);
                        finish();
                    }else {
                        if(head_select !=1 ) {
                            postImage(headPath);
                        }else {
                            systemHeadImg(headPosition);
                        }
                        InformationHeadActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                InformationHeadActivity.this.finish();
                            }
                        });
                    }
                } else {
                    Toast.makeText(InformationHeadActivity.this, "您还未选择头像", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.img_photo:
                head_select = 2;
                adapter_head.setHead_select(2);
                adapter_head.setLastPosition(-1);
                adapter_head.notifyDataSetChanged();
                Matisse.from(InformationHeadActivity.this) //Activity
                        .choose(MimeType.ofAll())//选择全部（包括视频）
                        .countable(true)  // 有序选择图片
                        .maxSelectable(1)  //最大选择数量为9
                        .gridExpectedSize(400)  //图片显示表格的大小
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)  //缩放比率
                        .theme(R.style.Matisse_Zhihu) //主题  暗色主题 R.style.Matisse_Dracula
                        .imageEngine(new GlideEngine()) //加载方式
                        .forResult(REQUEST_CODE_CHOOSE); //结果返回码 ，在onActivityResult中获取
                break;
            case R.id.img_album:
                img_album.setImageResource(R.drawable.img);
                head_select = 1;
                adapter_head.setHead_select(1);
                adapter_head.setLastPosition(-1);
                adapter_head.notifyDataSetChanged();
                head = "";
                Toast.makeText(InformationHeadActivity.this, "已取消选择", Toast.LENGTH_SHORT).show();
                break;

        }
    }

    public void systemHeadImg(int headPosition){
        switch ( headPosition ){
            case 0:
                Constans.u_head = Constans.MAN1;
                break;
            case 1:
                Constans.u_head = Constans.WOMAN1;
                break;
            case 2:
                Constans.u_head = Constans.MAN2;
                break;
            case 3:
                Constans.u_head = Constans.WOMAN2;
                break;
            case 4:
                Constans.u_head = Constans.MAN3;
                break;
            case 5:
                Constans.u_head = Constans.WOMAN3;
                break;
        }
        Log.i(TAG, "systemHeadImg: "+Constans.u_head);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = (ArrayList<Uri>) Matisse.obtainResult(data);
            // 获取content的内容，使用environment加入获取bitmap。附加到
            if (mSelected.size() == 1) {
                Uri uri = mSelected.get(0);
                String filePath = getRealPathFromUriAboveApi19(InformationHeadActivity.this, uri);
                Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                img_album.setImageBitmap(bitmap);
                headPath = filePath;
                head = headPath;
                head_select = 2;
                adapter_head.setHead_select(2);
                adapter_head.setLastPosition(-1);
                adapter_head.notifyDataSetChanged();
            }
        }
    }

    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                // 使用':'分割
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }

    /**
     * 获取数据库表中的 _data 列，即返回Uri对应的文件路径
     *
     * @return
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[]
            selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public void postImage(String realFilePath){
        File file = new File(realFilePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile",file.getName(),requestBody);
        Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(HttpUtil.FILE_ADDRESS).build();
        retrofit.create(HttpUpload.class).uploadUserHeadImg(part).enqueue(new Callback<InformationHead>() {
            @Override
            public void onResponse(Call<InformationHead> call, Response<InformationHead> response) {
                if( response.isSuccessful() ) {
                    String url = response.body().getData().getUrl();
                    Constans.u_head = url;
                    Toast.makeText(InformationHeadActivity.this,"修改头像成功",Toast.LENGTH_SHORT);
                }else {
                    Toast.makeText(InformationHeadActivity.this,"修改头像失败",Toast.LENGTH_SHORT);
                }

            }
            @Override
            public void onFailure(Call<InformationHead> call, Throwable t) {
                Toast.makeText(InformationHeadActivity.this,"修改头像失败",Toast.LENGTH_SHORT);
            }
        });
    }
}

